import type { BasicColumn } from '/@/vbenComponents/Table/src/types/table'

import { h, ref, Ref } from 'vue'

import EditableCell from './EditableCell.vue'
import { isArray } from '/@/utils/is'

// interface Params {
//   text: string
//   record: Recordable
//   index: number
// }
// 这里 新增一个 ref变量 用于监听record编辑状态的变化，否则点击编辑会 无效
const editChange = ref(false)
export function renderEditCell(column: BasicColumn) {
  // return ({ text: value, record, index }: Params) => {
  return (value: string, record: Recordable, index: number) => {
    editChange.value = record.edit
    record.onValid = async () => {
      if (isArray(record?.validCbs)) {
        const validFns = (record?.validCbs || []).map((fn) => fn())
        const res = await Promise.all(validFns)
        return res.every((item) => !!item)
      } else {
        return false
      }
    }

    record.onEdit = async (edit: boolean, submit = false) => {
      if (!submit) {
        record.editable = edit
        editChange.value = edit
      }

      if (!edit && submit) {
        if (!(await record.onValid())) return false
        const res = await record.onSubmitEdit?.()
        if (res) {
          record.editable = false
          return true
        }
        return false
      }
      // cancel
      if (!edit && !submit) {
        record.onCancelEdit?.()
      }
      return true
    }

    return h(EditableCell, {
      props: {
        value,
        record: { ...record, edit: editChange.value },
        column,
        index,
      },
    })
  }
}

export type EditRecordRow<T = Recordable> = Partial<
  {
    onEdit: (editable: boolean, submit?: boolean) => Promise<boolean>
    onValid: () => Promise<boolean>
    editable: boolean
    onCancel: Fn
    onSubmit: Fn
    submitCbs: Fn[]
    cancelCbs: Fn[]
    validCbs: Fn[]
    editValueRefs: Recordable<Ref>
  } & T
>
